﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;

namespace SiyinPractice.Application.ProjectManagement.ProjectManage.Help
{
    public class DingDingTimeCycleHelper
    {
        /// <summary>
        /// 服务专属计时器
        /// </summary>
        private Timer Timer;

        /// <summary>
        /// 默认计时器时间间隔1秒（提高计时器开始时间准确度）
        /// </summary>
    //    private double DefaultTimerInterval = 10 * 1000;

        /// <summary>
        /// 设置多个循环周期
        /// </summary>
        private TimeCycle TimeCycleList;

        public DingDingTimeCycleHelper()
        {
            this.Timer = new Timer();
        }

        //public async Task<List<AccountPasswordDto>> GetAccountPasswordDto()
        //{
        //    List<AccountPasswordDto> projectProgressDtos = new List<AccountPasswordDto>();
        //    var sql = string.Format($"123");
        //    //var para1 = new SqlParameter("begintime", projectProgressSearchPagedDto.BeginTime);
        //    //var para2 = new SqlParameter("endtime", projectProgressSearchPagedDto.EndTime);

        //    SqlParameter[] parameters = new SqlParameter[] { };
        //    //object[] parameters=new object[begintime, endtime];
        //    var table = await _baseDbContext.ExecuteQuery(sql, null);
        //    //for (int i = 0; i < table.Rows.Count; i++)
        //    //{
        //    //}

        //    return projectProgressDtos;
        //}

        /// <summary>
        /// 更新一个计时器的计时周期
        /// </summary>
        /// <param name="newTimerInterval">新的计时周期</param>
        /// <param name="isFirstStart">是否是首次更新计时器周期</param>
        private void UpdateTimeInterval(double newTimerInterval, bool isFirstStart = false)
        {
            if (this.Timer != null && newTimerInterval > 0)
            {
                Timer.Stop();
                if (this.Timer.Interval != newTimerInterval)
                {
                    this.Timer.Interval = newTimerInterval;
                }
                if (isFirstStart)
                {
                    this.Timer.Elapsed += new ElapsedEventHandler(ServiceAction);
                }
                this.Timer.AutoReset = true;
                this.Timer.Start();
            }
        }

        /// <summary>
        /// 内部辅助方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ServiceAction(object sender, ElapsedEventArgs e)
        {
            Task.Run(() => TimeCycleList.Action());
            //List<TimeCycle> currentTimeCycleList = new List<TimeCycle>(0);
            //foreach (TimeCycle timeCycle in this.TimeCycleList)
            //    //timeCycle.Action
            //    Task.Run(() => timeCycle.Action());
            //currentTimeCycleList.Add(timeCycle);
            //DateTime now = DateTime.Now;
            //DateTime cycleBeginTime;
            //DateTime cycleEndTime;
            //foreach (TimeCycle timeCycle in this.TimeCycleList)
            //{
            //    cycleBeginTime = Convert.ToDateTime(timeCycle.BeginTime);
            //    cycleBeginTime = now.Date.AddHours(cycleBeginTime.Hour).AddMinutes(cycleBeginTime.Minute).AddSeconds(cycleBeginTime.Second);
            //    cycleEndTime = Convert.ToDateTime(timeCycle.EndTime);
            //    cycleEndTime = now.Date.AddHours(cycleEndTime.Hour).AddMinutes(cycleEndTime.Minute).AddSeconds(cycleEndTime.Second);
            //    if (cycleEndTime < cycleBeginTime)
            //    {
            //        cycleEndTime = cycleEndTime.AddDays(1);
            //    }

            //    if (now >= cycleBeginTime && now <= cycleEndTime)
            //    {
            //        //有最大执行次数限制或者没有限制
            //        if (timeCycle.ActionExecutionTimes < timeCycle.MaxActionTimes || timeCycle.MaxActionTimes == 0)
            //        {
            //            TimeSpan timeSpan = now - cycleBeginTime;
            //            bool isCanAction = (int)timeSpan.TotalSeconds % timeCycle.ActionSeconds == 0 ? true : false;
            //            if (isCanAction)
            //            {
            //                timeCycle.ActionExecutionTimes++;
            //                currentTimeCycleList.Add(timeCycle);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        //不在计时周期内，已执行次数清零
            //        timeCycle.ActionExecutionTimes = 0;
            //    }
            //}
            ////找到当前循环周期后，执行周期内动作
            //if (currentTimeCycleList.Count > 0)
            //{
            //    currentTimeCycleList.ForEach(item =>
            //    {
            //        //使用多线程执行任务，让代码快速执行
            //        Task.Run(() => item.Action());
            //    });
            //}
            //currentTimeCycleList.ForEach(item =>
            //{
            //    //使用多线程执行任务，让代码快速执行
            //    Task.Run(() => item.Action());
            //});
        }

        /// <summary>
        /// 开启计时器
        /// </summary>
        /// <param name="timeCycleArray"></param>
        public void Start( double DefaultTimerInterval, TimeCycle timeCycleArray)
        {
            if (timeCycleArray != null)
            {
                //if (this.TimeCycleList == null)
                //{
                //    this.TimeCycleList =new TimeCycle(new System.Guid,);
                //}
                this.TimeCycleList = timeCycleArray;

                //设置首次计时器周期（首次动作执行，是在计时器启动后在设置的时间间隔后做出的动作）
                this.UpdateTimeInterval(DefaultTimerInterval, true);
            }
        }

        /// <summary>
        /// 结束计时器
        /// </summary>
        public void Stop()
        {
            this.Timer.Stop();
        }
    }
}